package com.zhugang.week10;

import java.util.Arrays;

/**
 * @program algorithms
 * @description: canPartition
 * @author: chanzhugang
 * @create: 2022/08/29 13:44
 */
public class CanPartition2 {

    /**
     * 416 分割等和子集
     *
     * @param nums
     * @return
     */
    public boolean canPartition(int[] nums) {
        // 一个子集元素和为总和一半，往子集放元素，抽象成0-1背包问题，背包是否能正好装满
        int sum;
        int n = nums.length;
        sum = Arrays.stream(nums, 0, n).sum();
        if (sum % 2 == 1) {
            // 奇数不满足
            return false;
        }
        sum = sum / 2;
        // 定义状态及初始化第一行
        boolean[][] dp = new boolean[n][sum + 1];
        dp[0][0] = true;
        if (nums[0] <= sum) {
            dp[0][nums[0]] = true;
        }

        // 状态转移方程
        for (int i = 1; i < n; i++) {
            for (int j = 0; j <= sum; j++) {
                if (j - nums[i] >= 0) {
                    dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i]];
                } else {
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }
        return dp[n - 1][sum];
    }
}